<template>
  <doc-alert title="【交易】交易订单" url="https://doc.iocoder.cn/mall/trade-order/" />
  <doc-alert title="【交易】购物车" url="https://doc.iocoder.cn/mall/trade-cart/" />

  <ContentWrap>
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item v-show="false" label="hideId">
        <el-input v-model="formData.id" />
      </el-form-item>
      <el-tabs>
        <!-- 售后 -->
        <el-tab-pane label="售后">
          <el-form-item label="退货收货人姓名" prop="refundName">
            <el-input v-model="formData.refundName" class="!w-xs" />
            <el-text class="w-full" size="small" type="info">
              用户退货退款后台同意之后，显示在退货订单详情显示的接受退货的人员姓名</el-text
            >
          </el-form-item>
          <el-form-item label="退货收货人电话" prop="refundPhone">
            <el-input v-model="formData.refundPhone" class="!w-xs" />
            <el-text class="w-full" size="small" type="info">
              用户退货退款后台同意之后，显示在退货订单详情显示的接受退货的人员电话</el-text
            >
          </el-form-item>
          <el-form-item label="退货收货人地址" prop="refundAddress">
            <el-input v-model="formData.refundAddress" class="!w-xs" />
            <el-text class="w-full" size="small" type="info">
              用户退货退款后台同意之后，显示在退货订单详情显示的接受退货的地址信息</el-text
            >
          </el-form-item>
          <el-form-item label="退款理由" prop="afterSaleRefundReasons">
            <el-select
              v-model="formData.afterSaleRefundReasons"
              allow-create
              filterable
              multiple
              class="!w-xs"
              placeholder="请直接输入退款理由"
            >
              <el-option
                v-for="reason in formData.afterSaleRefundReasons"
                :key="reason"
                :label="reason"
                :value="reason"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="退货理由" prop="afterSaleReturnReasons">
            <el-select
              v-model="formData.afterSaleReturnReasons"
              allow-create
              filterable
              multiple
              class="!w-xs"
              placeholder="请直接输入退货理由"
            >
              <el-option
                v-for="reason in formData.afterSaleReturnReasons"
                :key="reason"
                :label="reason"
                :value="reason"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="退还优惠券" prop="couponReturnOpen">
            <el-switch v-model="formData.couponReturnOpen" style="user-select: none" />
            <el-text class="w-full" size="small" type="info">
              优惠券是否退回开关，商品成功退款后，退回/不退回使用的优惠券</el-text
            >
          </el-form-item>
          <el-form-item label="售后期限" prop="refundTimeAvailable">
            <el-input-number
              v-model="formData.refundTimeAvailable"
              :min="0"
              :precision="0"
              class="!w-xs"
            />
            <el-text class="w-full" size="small" type="info">
              订单收货之后，在多少天内可以进行退款，超出天数前端不显示退款按钮，设置0则永远显示</el-text
            >
          </el-form-item>
        </el-tab-pane>
        <!-- 配送 -->
        <el-tab-pane label="配送">
          <el-form-item label="启用包邮" prop="deliveryExpressFreeEnabled">
            <el-switch v-model="formData.deliveryExpressFreeEnabled" style="user-select: none" />
            <el-text class="w-full" size="small" type="info"> 商城是否启用全场包邮</el-text>
          </el-form-item>
          <el-form-item label="满额包邮" prop="deliveryExpressFreePrice">
            <el-input-number
              v-model="formData.deliveryExpressFreePrice"
              :min="0"
              :precision="2"
              class="!w-xs"
              placeholder="请输入满额包邮"
            />
            <el-text class="w-full" size="small" type="info">
              商城商品满多少金额即可包邮，单位：元
            </el-text>
          </el-form-item>
          <el-form-item label="启用门店自提" prop="deliveryPickUpEnabled">
            <el-switch v-model="formData.deliveryPickUpEnabled" style="user-select: none" />
          </el-form-item>
        </el-tab-pane>
        <!-- 分销 -->
        <el-tab-pane label="分销">
          <el-form-item label="分佣启用" prop="brokerageEnabled">
            <el-switch v-model="formData.brokerageEnabled" style="user-select: none" />
            <el-text class="w-full" size="small" type="info"> 商城是否开启分销模式</el-text>
          </el-form-item>
          <template v-if="formData.brokerageEnabled">
            <el-form-item label="分佣模式" prop="brokerageEnabledCondition">
              <el-radio-group v-model="formData.brokerageEnabledCondition">
                <el-radio
                  v-for="dict in getIntDictOptions(DICT_TYPE.BROKERAGE_ENABLED_CONDITION)"
                  :key="dict.value"
                  :value="dict.value"
                >
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
              <el-text class="w-full" size="small" type="info">
                人人分销：每个用户都可以成为推广员
              </el-text>
              <el-text class="w-full" size="small" type="info">
                指定分销：仅可在后台手动设置推广员
              </el-text>
            </el-form-item>
            <el-form-item label="分销关系绑定" prop="brokerageBindMode">
              <el-radio-group v-model="formData.brokerageBindMode">
                <el-radio
                  v-for="dict in getIntDictOptions(DICT_TYPE.BROKERAGE_BIND_MODE)"
                  :key="dict.value"
                  :value="dict.value"
                >
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
              <el-text class="w-full" size="small" type="info">
                首次绑定：只要用户没有推广人，随时都可以绑定推广关系
              </el-text>
              <el-text class="w-full" size="small" type="info">
                注册绑定：只有新用户注册时或首次进入系统时才可以绑定推广关系
              </el-text>
            </el-form-item>
            <el-form-item label="分销海报图">
              <UploadImgs v-model="formData.brokeragePosterUrls" height="125px" width="75px" />
              <el-text class="w-full" size="small" type="info">
                个人中心分销海报图片，建议尺寸 600x1000
              </el-text>
            </el-form-item>
            <el-form-item label="一级返佣比例" prop="brokerageFirstPercent">
              <el-input-number
                v-model="formData.brokerageFirstPercent"
                :max="100"
                :min="0"
                class="!w-xs"
                placeholder="请输入一级返佣比例"
              />
              <el-text class="w-full" size="small" type="info">
                订单交易成功后给推广人返佣的百分比
              </el-text>
            </el-form-item>
            <el-form-item label="二级返佣比例" prop="brokerageSecondPercent">
              <el-input-number
                v-model="formData.brokerageSecondPercent"
                :max="100"
                :min="0"
                class="!w-xs"
                placeholder="请输入二级返佣比例"
              />
              <el-text class="w-full" size="small" type="info">
                订单交易成功后给推广人的推荐人返佣的百分比
              </el-text>
            </el-form-item>
            <el-form-item label="佣金冻结天数" prop="brokerageFrozenDays">
              <el-input-number
                v-model="formData.brokerageFrozenDays"
                :min="0"
                class="!w-xs"
                placeholder="请输入佣金冻结天数"
              />
              <el-text class="w-full" size="small" type="info">
                防止用户退款，佣金被提现了，所以需要设置佣金冻结时间，单位：天
              </el-text>
              <el-text class="w-full" size="small" type="info">
                当下线在商城有成交，订单支付之后推广佣金处于冻结期，待冻结期过了没有发生售后相关情况，佣金给予推广员解冻，已解冻的佣金才支持提现；若冻结期间发生售后，冻结佣金会进行收回；若解冻之后发生售后，已解冻佣金不进行收回，损失由商家承担。
              </el-text>
            </el-form-item>
            <el-form-item label="提现最低金额" prop="brokerageWithdrawMinPrice">
              <el-input-number
                v-model="formData.brokerageWithdrawMinPrice"
                :min="0"
                :precision="2"
                class="!w-xs"
                placeholder="请输入提现最低金额"
              />
              <el-text class="w-full" size="small" type="info">
                用户提现最低金额限制，单位：元
              </el-text>
            </el-form-item>
            <el-form-item label="提现手续费" prop="brokerageWithdrawFeePercent">
              <el-input-number
                v-model="formData.brokerageWithdrawFeePercent"
                :max="100"
                :min="0"
                class="!w-xs"
                placeholder="请输入提现手续费"
              />
              <el-text class="w-full" size="small" type="info">
                提现手续费百分比，范围 0-100，0 为无提现手续费。例：设置 10，即收取 10% 手续费，提现
                10 元，到账 9 元，1 元手续费
              </el-text>
            </el-form-item>
            <el-form-item label="提现方式" prop="brokerageWithdrawTypes">
              <el-checkbox-group v-model="formData.brokerageWithdrawTypes">
                <el-checkbox
                  v-for="dict in getIntDictOptions(DICT_TYPE.BROKERAGE_WITHDRAW_TYPE)"
                  :key="dict.value"
                  :value="dict.value"
                >
                  {{ dict.label }}
                </el-checkbox>
              </el-checkbox-group>
              <el-text class="w-full" size="small" type="info"> 商城开通提现的付款方式</el-text>
            </el-form-item>
          </template>
        </el-tab-pane>
        <el-tab-pane label="代理">
          <el-form-item label="代理启用" prop="brokerageAgentEnabled">
            <el-switch v-model="formData.brokerageAgentEnabled" style="user-select: none" />
            <el-text class="w-full" size="small" type="info"> 商城是否开启代理模式</el-text>
          </el-form-item>
        </el-tab-pane>
        <!-- 发票 -->
        <!-- <el-tab-pane label="发票">
          <el-form-item label="发票功能启用" prop="invoiceEnabled">
            <el-switch v-model="formData.invoiceEnabled" style="user-select: none" />
            <el-text class="w-full" size="small" type="info"> 是否启用发票功能</el-text>
          </el-form-item>
          <el-form-item label="专用发票启用" prop="invoiceSpecialEnabled">
            <el-switch v-model="formData.invoiceSpecialEnabled" style="user-select: none" />
            <el-text class="w-full" size="small" type="info"> 是否启用专用发票功能</el-text>
          </el-form-item>
        </el-tab-pane> -->
        <!-- 订单取消配置 -->
        <el-tab-pane label="订单取消配置">
          <el-form-item label="普通未支付订单取消" prop="payGeneralExpireTime" label-width="150">
            <el-input-number
              v-model="formData.payGeneralExpireTime"
              :min="0"
              :precision="0"
              class="!w-xs"
            />
            <el-text class="w-full" size="small" type="info">
              普通商品未支付订单的自动取消时间，单位（分钟）</el-text
            >
          </el-form-item>
          <el-form-item label="活动未支付订单取消" prop="payDiscountExpireTime" label-width="150">
            <el-input-number
              v-model="formData.payDiscountExpireTime"
              :min="0"
              :precision="0"
              class="!w-xs"
            />
            <el-text class="w-full" size="small" type="info">
              活动商品未支付的订单自动取消时间，单位（分钟）</el-text
            >
          </el-form-item>
          <el-form-item label="砍价未支付订单取消" prop="payBargainExpireTime" label-width="150">
            <el-input-number
              v-model="formData.payBargainExpireTime"
              :min="0"
              :precision="0"
              class="!w-xs"
            />
            <el-text class="w-full" size="small" type="info">
              砍价未支付订单自动取消时间，单位（分钟），如果为0将使用默认活动取消时间，优先使用单独活动配置</el-text
            >
          </el-form-item>
          <el-form-item label="秒杀未支付订单取消" prop="paySeckillExpireTime" label-width="150">
            <el-input-number
              v-model="formData.paySeckillExpireTime"
              :min="0"
              :precision="0"
              class="!w-xs"
            />
            <el-text class="w-full" size="small" type="info">
              秒杀未支付订单自动取消时间，单位（分钟），如果为0将使用默认活动取消时间，优先使用单独活动配置</el-text
            >
          </el-form-item>
          <el-form-item
            label="拼团未支付订单取消"
            prop="payCombinationExpireTime"
            label-width="150"
          >
            <el-input-number
              v-model="formData.payCombinationExpireTime"
              :min="0"
              :precision="0"
              class="!w-xs"
            />
            <el-text class="w-full" size="small" type="info">
              拼团未支付订单自动取消时间，单位（分钟），如果为0将使用默认活动取消时间，优先使用单独活动配置</el-text
            >
          </el-form-item>
        </el-tab-pane>
        <!-- 自动收货配置 -->
        <el-tab-pane label="自动收货配置">
          <el-form-item label="自动收货时间" prop="deliveryAutomaticTime" label-width="150">
            <el-input-number
              v-model="formData.deliveryAutomaticTime"
              :min="0"
              :precision="0"
              class="!w-xs"
            />
            <el-text class="w-full" size="small" type="info">
              商城订单发货之后，用户如果不手动点击收货，则在N天后自动收货，设置0为不自动收货，单位（天）</el-text
            >
          </el-form-item>
        </el-tab-pane>
        <!-- 自动评价配置 -->
        <el-tab-pane label="自动评价时间">
          <el-form-item label="自动评价时间" prop="evaluationAutomaticTime" label-width="150">
            <el-input-number
              v-model="formData.evaluationAutomaticTime"
              :min="0"
              :precision="0"
              class="!w-xs"
            />
            <el-text class="w-full" size="small" type="info">
              商城订单在收货之后，用户如果不主动评价订单商品，则在N天后自动评价，设置0为永远不自动评价，单位（天）</el-text
            >
          </el-form-item>
          <el-form-item label="自动评价文字" prop="evaluationAutomaticWord" label-width="150">
            <el-input v-model="formData.evaluationAutomaticWord" class="!w-xs" />
            <el-text class="w-full" size="small" type="info"> 自动评价显示的评价文字</el-text>
          </el-form-item>
        </el-tab-pane>
        <!-- 寄存设置 -->
        <el-tab-pane label="寄存提货设置">
          <el-form-item label="自动寄存" prop="storageAutomatic">
            <el-switch v-model="formData.storageAutomatic" style="user-select: none" />
            <el-text class="w-full" size="small" type="info"> 是否开启自动寄存</el-text>
          </el-form-item>
          <template v-if="formData.storageAutomatic">
            <!-- <el-form-item label="寄存方式" prop="storageSetupType">
              <el-radio-group v-model="formData.storageSetupType">
                <el-radio :value="0"> 自动寄存 </el-radio>
                <el-radio :value="1"> 手动寄存 </el-radio>
              </el-radio-group>
            </el-form-item> -->
            <!-- <template v-if="formData.storageSetupType == 1">
              <el-form-item label="寄存设置" prop="storageSetup">
                <el-radio-group v-model="formData.storageSetup">
                  <el-radio :value="0"> 关联订单 </el-radio>
                  <el-radio :value="1"> 不关联订单 </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                label="欠款商品寄存"
                prop="storageSetup"
                v-if="formData.storageSetup == 0"
              >
                <el-radio-group v-model="formData.storageSetup">
                  <el-radio :value="0"> 自动寄存 </el-radio>
                  <el-radio :value="1"> 手动寄存 </el-radio>
                </el-radio-group>
              </el-form-item>
            </template> -->

            <el-form-item label="寄存时效" prop="storageExpireTime">
              <el-input-number
                v-model="formData.storageExpireTime"
                :min="0"
                :precision="0"
                class="!w-xs"
              />
              <el-text class="w-full" size="small" type="info"> 单位（天）</el-text>
            </el-form-item>
          </template>
          <el-divider border-style="dashed" />
          <el-form-item label="提货验证密码" prop="deliveryVerification">
            <el-radio-group v-model="formData.deliveryVerification">
              <el-radio :value="1"> 验证 </el-radio>
              <el-radio :value="0"> 不验证 </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="订单补录配置">
          <el-form-item label="补录开关" prop="repairEnable" label-width="150">
            <el-switch v-model="formData.repairEnable" style="user-select: none" />
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="评价内容配置">
          <el-form-item label="评价标签" prop="evaluateListConfig" label-width="150">
            <div class="flex gap-2">
              <el-tag
                v-for="tag in formData.evaluateListConfig"
                :key="tag"
                size="large"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="inputVisible"
                ref="InputRef"
                v-model="inputValue"
                class="w-20"
                @keyup.enter="handleInputConfirm"
                @blur="handleInputConfirm"
              />
              <el-button v-else class="button-new-tag" @click="showInput">
                + 添加评价标签
              </el-button>
            </div>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>

      <!-- 保存 -->
      <el-form-item>
        <el-button :loading="formLoading" type="primary" @click="submitForm"> 保存</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>

<script lang="ts" setup>
import * as ConfigApi from '@/api/mall/trade/config'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { InputInstance } from 'element-plus'
import { cloneDeep } from 'lodash-es'

defineOptions({ name: 'TradeConfig' })

const message = useMessage() // 消息弹窗

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formRef = ref()
const formData = ref({
  id: null,
  refundName: '',
  refundPhone: '',
  refundAddress: '',
  couponReturnOpen: false,
  refundTimeAvailable: 0,
  afterSaleRefundReasons: [],
  afterSaleReturnReasons: [],
  deliveryExpressFreeEnabled: false,
  deliveryExpressFreePrice: 0,
  deliveryPickUpEnabled: false,
  brokerageEnabled: false,
  brokerageAgentEnabled: false, //代理开关
  brokerageEnabledCondition: undefined,
  brokerageBindMode: undefined,
  brokeragePosterUrls: [],
  brokerageFirstPercent: 0,
  brokerageSecondPercent: 0,
  brokerageWithdrawMinPrice: 0,
  brokerageWithdrawFeePercent: 0,
  brokerageFrozenDays: 0,
  brokerageWithdrawTypes: [],
  invoiceEnabled: false,
  invoiceSpecialEnabled: false,
  payGeneralExpireTime: 1,
  payDiscountExpireTime: 1,
  payBargainExpireTime: 1,
  paySeckillExpireTime: 1,
  payCombinationExpireTime: 1,
  deliveryAutomaticTime: 7,
  evaluationAutomaticTime: 0,
  evaluationAutomaticWord: '此用户未做评价',
  deliveryVerification: 0,
  storageExpireTime: 7,
  storageSetup: 1,
  storageSetupType: 0,
  storageAutomatic: false,
  repairEnable: false,
  evaluateListConfig: [] //评价配置列表
})
const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref<InputInstance>()

const handleClose = (tag: string) => {
  formData.value.evaluateListConfig.splice(formData.value.evaluateListConfig.indexOf(tag), 1)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    formData.value.evaluateListConfig.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}
const formRules = reactive({
  deliveryExpressFreePrice: [{ required: true, message: '满额包邮不能为空', trigger: 'blur' }],
  brokerageEnabledCondition: [{ required: true, message: '分佣模式不能为空', trigger: 'blur' }],
  brokerageBindMode: [{ required: true, message: '分销关系绑定模式不能为空', trigger: 'blur' }],
  brokerageFirstPercent: [{ required: true, message: '一级返佣比例不能为空', trigger: 'blur' }],
  brokerageSecondPercent: [{ required: true, message: '二级返佣比例不能为空', trigger: 'blur' }],
  brokerageWithdrawMinPrice: [
    { required: true, message: '用户提现最低金额不能为空', trigger: 'blur' }
  ],
  brokerageWithdrawFeePercent: [{ required: true, message: '提现手续费不能为空', trigger: 'blur' }],
  brokerageFrozenDays: [{ required: true, message: '佣金冻结时间不能为空', trigger: 'blur' }],
  brokerageWithdrawTypes: [
    {
      required: true,
      message: '提现方式不能为空',
      trigger: 'change'
    }
  ]
})

const submitForm = async () => {
  if (formLoading.value) return
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = cloneDeep(unref(formData.value)) as unknown as ConfigApi.ConfigVO
    // 金额放大
    data.deliveryExpressFreePrice = data.deliveryExpressFreePrice * 100
    data.brokerageWithdrawMinPrice = data.brokerageWithdrawMinPrice * 100
    await ConfigApi.saveTradeConfig(data)
    message.success('保存成功')
  } finally {
    formLoading.value = false
  }
}

/** 查询交易中心配置 */
const getConfig = async () => {
  formLoading.value = true
  try {
    const data = await ConfigApi.getTradeConfig()
    if (data != null) {
      formData.value = data
      if (!formData.value.evaluateListConfig) {
        formData.value.evaluateListConfig = []
      }

      // 金额缩小
      formData.value.deliveryExpressFreePrice = data.deliveryExpressFreePrice / 100
      formData.value.brokerageWithdrawMinPrice = data.brokerageWithdrawMinPrice / 100
    }
  } finally {
    formLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getConfig()
})
</script>
